package com.ruoyi.trade.service.impl;

import com.ruoyi.trade.domain.CostGrid;
import com.ruoyi.trade.domain.GridRequest;
import com.ruoyi.trade.domain.TradeBaseGrid;
import com.ruoyi.trade.mapper.CostGridMapper;
import com.ruoyi.trade.mapper.RollingShortDateConfigMapper;
import com.ruoyi.trade.mapper.TradeBaseGridMapper;
import com.ruoyi.trade.service.ITradeBaseGridService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 交易基础网格Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-03
 */
@Service
public class TradeBaseGridServiceImpl implements ITradeBaseGridService {
    @Autowired
    private TradeBaseGridMapper tradeBaseGridMapper;

    @Autowired
    private CostGridMapper costGridMapper;

    @Autowired
    private RollingShortDateConfigMapper dateConfigMapper;

    /**
     * 查询交易基础网格
     *
     * @param id 交易基础网格主键
     * @return 交易基础网格
     */
    @Override
    public TradeBaseGrid selectTradeBaseGridById(Long id) {
        return tradeBaseGridMapper.selectTradeBaseGridById(id);
    }

    /**
     * 查询交易基础网格列表
     *
     * @param tradeBaseGrid 交易基础网格
     * @return 交易基础网格
     */
    @Override
    public List<TradeBaseGrid> selectTradeBaseGridList(TradeBaseGrid tradeBaseGrid) {
        return tradeBaseGridMapper.selectTradeBaseGridList(tradeBaseGrid);
    }

    /**
     * 新增交易基础网格
     *
     * @param tradeBaseGrid 交易基础网格
     * @return 结果
     */
    @Override
    public int insertTradeBaseGrid(TradeBaseGrid tradeBaseGrid) {
        return tradeBaseGridMapper.insertTradeBaseGrid(tradeBaseGrid);
    }

    /**
     * 修改交易基础网格
     *
     * @param tradeBaseGrid 交易基础网格
     * @return 结果
     */
    @Override
    public int updateTradeBaseGrid(TradeBaseGrid tradeBaseGrid) {
        return tradeBaseGridMapper.updateTradeBaseGrid(tradeBaseGrid);
    }

    /**
     * 批量删除交易基础网格
     *
     * @param ids 需要删除的交易基础网格主键
     * @return 结果
     */
    @Override
    public int deleteTradeBaseGridByIds(Long[] ids) {
        return tradeBaseGridMapper.deleteTradeBaseGridByIds(ids);
    }

    /**
     * 删除交易基础网格信息
     *
     * @param id 交易基础网格主键
     * @return 结果
     */
    @Override
    public int deleteTradeBaseGridById(Long id) {
        return tradeBaseGridMapper.deleteTradeBaseGridById(id);
    }

    /**
     * 生成网格数据（使用未参与计算的数据）
     *
     * @param gridRequest 网格请求参数
     * @return 结果
     */
    @Override
    public int generateGrid(GridRequest gridRequest) {
        // 查询cost_grid表中未参与计算的数据
        List<CostGrid> costGridList = costGridMapper.selectUnCalculatedCostGridList(new CostGrid());
        
        // 添加非空校验，如果查询到的list为空，抛出异常
        if (costGridList == null || costGridList.isEmpty()) {
            throw new RuntimeException("成本网格中没有需要计算的数据");
        }
        
        // 存储需要单独处理的数据和需要合并处理的数据
        List<CostGrid> individualGrids = new ArrayList<>();
        List<List<CostGrid>> groupsToMerge = new ArrayList<>();
        
        // 按独立运营组分组处理（只处理独立运营标识为1且独立运营组不为null的数据）
        Map<Long, List<CostGrid>> groupMap = costGridList.stream()
                .filter(costGrid -> costGrid.getIndependentFlag() != null && costGrid.getIndependentFlag() == 1 
                        && costGrid.getIndependentGroup() != null)
                .collect(Collectors.groupingBy(CostGrid::getIndependentGroup));
        
        // 处理有独立运营组标识且独立运营组相同的数据
        for (Map.Entry<Long, List<CostGrid>> entry : groupMap.entrySet()) {
            List<CostGrid> groupList = entry.getValue();
            if (groupList.size() >= 2) {
                // 需要合并的数据组
                groupsToMerge.add(groupList);
            } else {
                // 单独的数据
                individualGrids.addAll(groupList);
            }
        }
        
        // 处理没有独立运营组标识或者独立运营组为null的数据
        // 但需要特殊处理：即使independent_flag为null，如果independent_group相同且有多个数据，也需要合并
        Map<Long, List<CostGrid>> noGroupMap = costGridList.stream()
                .filter(costGrid -> costGrid.getIndependentGroup() != null && 
                        (costGrid.getIndependentFlag() == null || costGrid.getIndependentFlag() == 0))
                .collect(Collectors.groupingBy(CostGrid::getIndependentGroup));
        
        // 处理没有独立运营标识但有独立运营组的数据
        for (Map.Entry<Long, List<CostGrid>> entry : noGroupMap.entrySet()) {
            List<CostGrid> groupList = entry.getValue();
            if (groupList.size() >= 2) {
                // 需要合并的数据组
                groupsToMerge.add(groupList);
            } else {
                // 单独的数据
                individualGrids.addAll(groupList);
            }
        }
        
        // 处理完全没有独立运营组信息的数据
        List<CostGrid> trulyNoGroupList = costGridList.stream()
                .filter(costGrid -> costGrid.getIndependentGroup() == null)
                .collect(Collectors.toList());
        individualGrids.addAll(trulyNoGroupList);
        
        // 生成trade_base_grid数据
        int result = 0;
        
        // 处理单独的数据
        for (CostGrid costGrid : individualGrids) {
            result += generateTradeBaseGrids(costGrid);
        }
        
        // 处理需要合并的数据组
        for (List<CostGrid> group : groupsToMerge) {
            result += generateMergedTradeBaseGrids(group);
        }

        // 获取所有参与计算的CostGrid的ID并更新计算标识
        List<Long> calculatedIds = costGridList.stream()
                .map(CostGrid::getId)
                .filter(id -> id != null)
                .collect(Collectors.toList());

        if (!calculatedIds.isEmpty()) {
            // 将List<Long>转换为Long[]数组
            Long[] idsArray = calculatedIds.toArray(new Long[0]);
            costGridMapper.updateCostGridCalculateFlagByIds(idsArray);
        }
        
        return result;
    }
    
    /**
     * 生成合并后的TradeBaseGrid数据
     * @param costGridList 需要合并的CostGrid列表
     * @return 生成的记录数
     */
    private int generateMergedTradeBaseGrids(List<CostGrid> costGridList) {
        if (costGridList.isEmpty()) {
            return 0;
        }
        
        // 计算合并后的总数量和加权平均实际成交价
        long totalQuantity = 0;
        BigDecimal totalWeightedValue = BigDecimal.ZERO;
        
        for (CostGrid costGrid : costGridList) {
            if (costGrid.getQuantity() != null && costGrid.getActualTradePrice() != null) {
                totalQuantity += costGrid.getQuantity();
                BigDecimal quantity = new BigDecimal(costGrid.getQuantity());
                BigDecimal weightedValue = quantity.multiply(costGrid.getActualTradePrice());
                totalWeightedValue = totalWeightedValue.add(weightedValue);
            }
        }
        
        if (totalQuantity <= 0) {
            return 0;
        }
        
        // 计算加权平均实际成交价
        BigDecimal averagePrice = totalWeightedValue.divide(new BigDecimal(totalQuantity), 2, BigDecimal.ROUND_HALF_UP);
        
        // 计算网格价格：实际成交价除以10后向上取整
        BigDecimal gridPriceDecimal = averagePrice.divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP);
        long gridPrice = gridPriceDecimal.setScale(0, BigDecimal.ROUND_UP).longValue();
        
        // 计算网格节点价位：网格价格除以10后向上取整
        BigDecimal gridNodePriceDecimal = new BigDecimal(gridPrice).divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP);
        long gridNodePrice = gridNodePriceDecimal.setScale(0, BigDecimal.ROUND_UP).longValue();
        
        // 生成连贯的等差数列
        long quantity = totalQuantity;
        long commonDifference = 10; // 公差为10
        
        // 计算等差数列的起始值
        long startValue;
        if (quantity % 2 == 1) {
            // 奇数个，网格节点价位位于最中间位置
            long middleIndex = quantity / 2;
            startValue = gridNodePrice - middleIndex * commonDifference;
        } else {
            // 偶数个，网格节点价位位于n/2的位置（即第n/2+1个位置，索引为n/2-1）
            long middleIndex = quantity / 2 - 1;
            startValue = gridNodePrice - middleIndex * commonDifference;
        }
        
        // 生成每个TradeBaseGrid记录，按照原始数据的数量分配
        int count = 0;
        long currentIndex = 0;
        
        for (CostGrid costGrid : costGridList) {
            if (costGrid.getQuantity() == null || costGrid.getQuantity() <= 0) {
                continue;
            }
            
            long currentQuantity = costGrid.getQuantity();
            for (int i = 0; i < currentQuantity; i++) {
                if (currentIndex >= quantity) {
                    break;
                }
                
                long currentNodePrice = startValue + currentIndex * commonDifference;
                
                TradeBaseGrid tradeBaseGrid = new TradeBaseGrid();
                tradeBaseGrid.setGridNodePrice(currentNodePrice);
                tradeBaseGrid.setQuantity(1L); // 每条数据数量为1
                tradeBaseGrid.setActualTradePrice(costGrid.getActualTradePrice());
                tradeBaseGrid.setGridPrice(new BigDecimal(gridPrice)); // 使用计算出的网格价格
                tradeBaseGrid.setFee(costGrid.getFee());
                tradeBaseGrid.setInvestmentId(costGrid.getInvestmentId());
                tradeBaseGrid.setInvestorName(costGrid.getInvestorName());
                tradeBaseGrid.setIndependentGroup(costGrid.getIndependentGroup());
                tradeBaseGrid.setCreatedAt(new Date());
                tradeBaseGrid.setUpdatedAt(new Date());
                
                // 插入到数据库
                int result = tradeBaseGridMapper.insertTradeBaseGrid(tradeBaseGrid);
                count += result;
                currentIndex++;
            }
        }
        
        return count;
    }
    
    /**
     * 根据CostGrid生成TradeBaseGrid数据
     * @param costGrid 成本网格数据
     * @return 生成的记录数
     */
    private int generateTradeBaseGrids(CostGrid costGrid) {
        if (costGrid.getQuantity() == null || costGrid.getQuantity() <= 0 || costGrid.getActualTradePrice() == null) {
            return 0;
        }
        
        // 计算网格价格：实际成交价除以10后向上取整
        BigDecimal actualTradePrice = costGrid.getActualTradePrice();
        BigDecimal gridPriceDecimal = actualTradePrice.divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP);
        long gridPrice = gridPriceDecimal.setScale(0, BigDecimal.ROUND_UP).longValue();
        
        // 计算网格节点价位：网格价格除以10后向上取整
        BigDecimal gridNodePriceDecimal = new BigDecimal(gridPrice).divide(BigDecimal.TEN, 2, BigDecimal.ROUND_HALF_UP);
        long gridNodePrice = gridNodePriceDecimal.setScale(0, BigDecimal.ROUND_UP).longValue();
        
        long quantity = costGrid.getQuantity();
        long commonDifference = 10; // 公差为10
        
        // 计算等差数列的起始值
        long startValue;
        if (quantity % 2 == 1) {
            // 奇数个，网格节点价位位于最中间位置
            long middleIndex = quantity / 2;
            startValue = gridNodePrice - middleIndex * commonDifference;
        } else {
            // 偶数个，网格节点价位位于n/2的位置（即第n/2+1个位置，索引为n/2）
            long middleIndex = quantity / 2 - 1;
            startValue = gridNodePrice - middleIndex * commonDifference;
        }
        
        // 生成每个TradeBaseGrid记录
        int count = 0;
        for (int i = 0; i < quantity; i++) {
            long currentNodePrice = startValue + i * commonDifference;
            
            TradeBaseGrid tradeBaseGrid = new TradeBaseGrid();
            tradeBaseGrid.setGridNodePrice(currentNodePrice);
            tradeBaseGrid.setQuantity(1L); // 每条数据数量为1
            tradeBaseGrid.setActualTradePrice(costGrid.getActualTradePrice());
            tradeBaseGrid.setGridPrice(new BigDecimal(gridPrice)); // 使用计算出的网格价格
            tradeBaseGrid.setFee(costGrid.getFee());
            tradeBaseGrid.setInvestmentId(costGrid.getInvestmentId());
            tradeBaseGrid.setInvestorName(costGrid.getInvestorName());
            tradeBaseGrid.setIndependentGroup(costGrid.getIndependentGroup());
            tradeBaseGrid.setCreatedAt(new Date());
            tradeBaseGrid.setUpdatedAt(new Date());
            
            // 插入到数据库
            int result = tradeBaseGridMapper.insertTradeBaseGrid(tradeBaseGrid);
            count += result;
        }
        
        return count;
    }
}